package com.insta.hibernate.DAO;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.insta.hibernate.model.Eleve;

public class EleveDAO {
	
	public static void createEleve(String nom, String prenom, Integer annee, String etudiant, Session conn){
		Transaction tx= null;
		try {
			tx= conn.beginTransaction();
			Eleve e = new Eleve(nom, prenom, annee, etudiant);
			conn.save(e);
			tx.commit();
		} catch (RuntimeException e) {
			if(tx!=null){
				tx.rollback();
			}
			throw e;
		}
		//conn.createQuery("INSERT INTO eleve VALUES ('"++"', '', '', '', '')");
	}
	
	public static Eleve getEleveById(String id, Session conn){
		Criteria criteria= conn.createCriteria(Eleve.class)
				.add(Restrictions.naturalId().set("idEtudiant", id))
				.setCacheable(true);
		return (Eleve) criteria.uniqueResult();
	}
	
	public static void addEmail(String id, String email, Session conn){
		Transaction tx= null;
		try {
			tx= conn.beginTransaction();
			Eleve eleve= getEleveById(id, conn);
			eleve.addEmailAddress(email);
			tx.commit();
		} catch (RuntimeException e) {
			if(tx!=null){
				tx.rollback();
			}
			throw e;
		}
	}
}